<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px" @submit.native.prevent>
      <el-form-item label="公司名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入公司名称"
          clearable
          @keyup.enter.native="handleQuery"
          maxlength="27"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['basic:company:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['basic:company:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="companyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="公司名称" align="center" prop="companyName" />
      <el-table-column label="公司简介" align="center" prop="introduction" />
      <el-table-column label="LOGO" align="center" prop="logoLink">
        <template v-slot="{row}"><el-image class="table-logo" :src="row.logoLink" :preview-src-list="[row.logoLink]" /></template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" >
        <template v-slot="{row}">{{labelNickName(row.createBy)}}</template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['basic:company:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['basic:company:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改公司表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="formModel" :rules="rules" label-width="80px" @submit.native.prevent>
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model.trim="form.companyName" placeholder="请输入" clearable maxlength="27"/>
        </el-form-item>
        <el-form-item label="公司简介" prop="introduction">
          <el-input type="textarea"
                    autosize
                    resize="none"
                    v-model.trim="form.introduction"
                    placeholder="请输入"
                    clearable
                    maxlength="255"
                    show-word-limit
          />
        </el-form-item>
        <el-form-item label="logo" prop="logoInfo">
          <el-upload class="avatar-uploader"
                     :show-file-list="false"
                     :action="logoUploadProps.action"
                     :headers="logoUploadProps.headers"
                     :before-upload="validLogo"
                     :on-success="handleUploadSuccess"
                     :on-error="handleUploadError">
            <div class="el-upload-list__item-thumbnail el-upload">
              <img v-if="form.logoLink" :src="form.logoLink" class="avatar">
              <i v-else class="el-icon-plus logo-uploader-icon"></i>
              <div v-if="form.logoLink" class="logo-edit-icon">
                <i class="el-icon-plus" :style="{ color: !form.logoLink ? '#DCDCDC' : '#FFFFFF' }"></i>
              </div>
            </div>
          </el-upload>
        </el-form-item>
<!--        <el-form-item label="logo文件id" prop="logoOssId">
          <el-input v-model="form.logoOssId" placeholder="请输入logo文件id" />
        </el-form-item>
        <el-form-item label="logo文件链接" prop="logoLink">
          <el-input v-model="form.logoLink" placeholder="请输入logo文件链接" />
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCompany, getCompany, delCompany, addCompany, updateCompany } from "@/api/basic/company";
import {mapGetters} from 'vuex'
import { nickName } from '@/mixins/nickName';

const imageType = ['image/png', 'image/jpeg']

export default {
  name: "Company",
  mixins: [nickName('companyList')],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公司表表格数据
      companyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        companyName: [
          { required: true, message: "公司名称不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (typeof value === 'string' && value.length > 64) {return callback(new Error('公司名称超过64字'))}
              callback()
            },
            trigger: 'blur'
          }
        ],
        introduction: [
          {
            validator: (rule, value, callback) => {
              if (typeof value === 'string' && value.length > 255) {return callback(new Error('公司简介超过255字'))}
              callback()
            },
            trigger: 'blur'
          }
        ],
        logoInfo: [
          { required: true, message: "logo不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (!value.logoOssId && !value.logoLink) {return callback(new Error('未读取到logo, 请上传'))}
              if (!value.logoOssId || !value.logoLink) {return callback(new Error('请上传logo！'))}
              callback()
            },
            trigger: 'blur'
          }
        ],
      }
    };
  },
  computed: {
    ...mapGetters(['token']),
    formModel() {
      return {
        companyName: this.form.companyName,
        introduction: this.form.introduction,
        logoInfo: {
          logoOssId: this.form.logoOssId,
          logoLink: this.form.logoLink
        }
      }
    },
    logoUploadProps() {
      return {
        action: process.env.VUE_APP_BASE_API + '/basic/company/logoUpload',
        headers: {
          Authorization: 'Bearer ' + this.token
        },
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询公司表列表 */
    getList() {
      this.loading = true;
      listCompany(this.queryParams).then(response => {
        this.companyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        companyId: undefined,
        companyName: undefined,
        introduction: undefined,
        logoOssId: undefined,
        logoLink: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.companyId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加公司";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const companyId = row.companyId || this.ids
      getCompany(companyId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改公司";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.companyId != null) {
            updateCompany(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addCompany(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const companyIds = row.companyId || this.ids;
      const tips = row.companyId ? '删除公司将会删除该公司的所有东西，确认删除该公司吗？' : '删除公司将会删除所选择公司的所有东西，确认删除所选择的公司吗？'
      this.$modal.confirm(tips).then(() => {
        this.loading = true;
        return delCompany(companyIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    validLogo(file) {
      if (!imageType.includes(file.type)) {
        this.$message.error('文件格式不正确，请上传[png、jpg]格式')
        return false
      }
      if (Math.floor((file.size / 1024)) > 200) {
        this.$message.error('上传图片大小不能超过200KB')
        return false
      }
      return true
    },
    handleUploadSuccess(res) {
      if (res.code === 200) {
        this.$message.success(res.msg)
        this.form.logoOssId = res.data.ossId
        this.form.logoLink = res.data.url
        this.$refs.form.clearValidate('logoInfo')
      } else {
        this.$message.error(res.msg)
      }
    },
    handleUploadError(err) {
      this.$message.error(err)
    }
  }
};
</script>

<style scoped lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.logo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.logo-edit-icon {
  display: none;
  position: absolute;
  z-index: 1;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  font-size: 20px;
  align-items: center;
  justify-content: center;
  background-color: rgba(0,0,0,.5);
}

.logo-edit-icon span {
  margin-left: 5px;
}

.el-upload:hover .logo-edit-icon {
  display: flex;
}

.table-logo {
  width: 60px;
  height: 60px;
}

.el-textarea::v-deep .el-input__count{
  display: inline-block;
  height: 20px;
  line-height: 20px;
  bottom: -20px;
}
</style>
